#pragma once
#include <unistd.h>

#include <deque>
#include <memory>
#include <queue>

#include "HttpConnection.h"
#include "MutexLock.h"
#include "NonCopyable.h"

class HttpConnection;

class TimerNode {  //可以理解为时间节点
 public:
  TimerNode(std::shared_ptr<HttpConnection> requestData, int timeout);
  ~TimerNode();
  TimerNode(TimerNode& tn);
  void update(int timeout);
  bool isValid();
  void clearReq();
  void setDeleted() { deleted_ = true; }
  bool isDeleted() const { return deleted_; }
  size_t getExpTime() const { return expiredTime_; }

 private:
  bool deleted_;
  size_t expiredTime_;
  std::shared_ptr<HttpConnection> SPHttpConnection;
};

struct TimerCmp {  //仿函数
  bool operator()(std::shared_ptr<TimerNode>& a,
                  std::shared_ptr<TimerNode>& b) const {
    return a->getExpTime() > b->getExpTime();
  }
};

class TimerManager {  //管理各个时间节点
 public:
  TimerManager();
  ~TimerManager();
  void addTimer(std::shared_ptr<HttpConnection> SPHttpConnection, int timeout);
  void handleExpiredEvent();

 private:
  typedef std::shared_ptr<TimerNode> SPTimerNode;
  std::priority_queue<SPTimerNode, std::deque<SPTimerNode>, TimerCmp>
      timerNodeQueue;
  // MutexLock lock;
};
